/**
 * @file name TBTaskActivity.java
 */
package com.digital.community;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.digital.community.common.bean.CommonBean;
import com.digital.community.common.bean.Dict;
import com.digital.community.common.bean.Dicts;
import com.digital.community.common.utils.ConnectWeb;
import com.digital.community.common.utils.HttpUtils;
import com.digital.community.common.utils.UnitsUtils;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.Parcelable;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.util.Log;
import android.view.Display;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.view.animation.TranslateAnimation;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

/**
 * 
 * @author yarine.gao
 * @date 2012-11-8
 * @version 1.0.0
 */
public class TBTaskActivity extends Activity implements OnClickListener{
	
	private ViewPager myViewPager;
	private MyPagerAdapter myAdapter;
	private List<View> mListViews;
	
	private View addLayout = null;
	private View newLayout = null;
	private View rebackLayout = null;
	private View backLayout = null;
	private View completeLayout = null;
	
	private LayoutInflater mInflater;
	
	private ImageView tranImg;
	private int tranImgWidth = 0;
	private int preIndex = 0;
	
	private ImageView[] cateIcon = null;
	private TextView[] cateTxt = null;
	Integer[] imgArrSelected = new Integer[5];
	Integer[] imgArrCommon = new Integer[5];
	//第一个页面的控件
	private TextView et_name;
	private Spinner add_sp_bigType;//任务大类
	private Spinner add_sp_smallType;//任务小类
	private EditText add_task_detail;//任务描述
	private EditText add_task_cardno;//任务附件
	private Button add_bt_add;//添加任务按钮
	private ProgressDialog proDialog;
	String result;
	JSONObject jsonObj;
	JSONArray array;//存放任务类型
	JSONArray taskArray;//存放任务集合
	private List<Dicts> parentDicts = new ArrayList<Dicts>();
	private List<String> parentDicetString = new ArrayList<String>();
	private List<String> sonDicetString = new ArrayList<String>();
	private List<Dict> sonDicts = new ArrayList<Dict>();
	Message msg;
    //适配器
    //父类适配器
    ArrayAdapter<String> parentAdapter ;
    //子类适配器
    ArrayAdapter<String> sonAdapter;
	private Handler handler = new Handler(){
		@Override
		public void handleMessage(Message msg) {
			proDialog.cancel();
			switch(msg.what){
			case 1:
				try {
					parentDicetString.clear();
					sonDicetString.clear();
					for(int i=0;i<array.length();i++){
						JSONObject jsonObj = new JSONObject(array.get(i).toString());
						parentDicetString.add(jsonObj.getJSONObject("dict").getString("dname"));
						//将第一个父类型的子类加入到子类列表中
						if(i==0){
							//得到该父类的子类型集合
							JSONArray sonDicts = new JSONArray(jsonObj.getString("dictList"));
							for(int m=0;m<sonDicts.length();m++){
								JSONObject jsonObj1 = new JSONObject(sonDicts.get(m).toString());
								sonDicetString.add(jsonObj1.getString("dname"));
							}
						}
					}
					
					add_sp_bigType.setAdapter(parentAdapter);
					add_sp_smallType.setAdapter(sonAdapter);
					
				} catch (JSONException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
					Toast.makeText(mContext, "载入失败！", Toast.LENGTH_SHORT).show();
//					finish();
				}
				break;
			case 2:
				Toast.makeText(mContext, "载入失败！", Toast.LENGTH_SHORT).show();
//				finish();
				break;
			case 3://刷新任务列表页面
				newTaskListView.setAdapter(taskListAdapter);
				taskListAdapter.notifyDataSetChanged();
				break;
			case 4://刷新任务列表页面
				jianduTaskListView.setAdapter(taskListAdapter);
				taskListAdapter.notifyDataSetChanged();
				break;
			case 5://刷新任务列表页面
				tuihuiTaskListView.setAdapter(taskListAdapter);
				taskListAdapter.notifyDataSetChanged();
				break;
			case 6://刷新任务列表页面
				doneTaskListView.setAdapter(taskListAdapter);
				taskListAdapter.notifyDataSetChanged();
				break;
			}
		}
	};
	
	 //初始化新任务页面
	ListView newTaskListView;
	ListView jianduTaskListView;
	ListView tuihuiTaskListView;
	ListView doneTaskListView;
	CommonBean commonBean;
	private Context mContext;
	public MyConstants myConstants = null;
	private File[] files = new File[4];
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.tbtask);
		commonBean  = (CommonBean)getApplicationContext();
		mContext = this;
		
		mInflater = getLayoutInflater();
		
		myAdapter = new MyPagerAdapter();
		addLayout = mInflater.inflate(R.layout.tbtask_add, null);
		newLayout = mInflater.inflate(R.layout.tbtask_new, null);
		rebackLayout = mInflater.inflate(R.layout.tbtask_reback, null);
		backLayout = mInflater.inflate(R.layout.tbtask_back, null);
		completeLayout = mInflater.inflate(R.layout.tbtask_complete, null);
		
		initDisplayInfo();
		
		mListViews = new ArrayList<View>();
		mListViews.add(addLayout);
		mListViews.add(newLayout);
		mListViews.add(rebackLayout);
		mListViews.add(backLayout);
		mListViews.add(completeLayout);
		
		cateIcon = new ImageView[5];
		cateTxt = new TextView[5];
		
		cateIcon[0] = (ImageView)findViewById(R.id.img_task_add);
		cateTxt[0] = (TextView)findViewById(R.id.txt_task_add);
		
		cateIcon[1] = (ImageView)findViewById(R.id.img_task_new);
		cateTxt[1] = (TextView)findViewById(R.id.txt_task_new);
		
		cateIcon[2] = (ImageView)findViewById(R.id.img_reback);
		cateTxt[2] = (TextView)findViewById(R.id.txt_reback);
		
		cateIcon[3] = (ImageView)findViewById(R.id.img_task_back);
		cateTxt[3] = (TextView)findViewById(R.id.txt_task_back);
		
		cateIcon[4] = (ImageView)findViewById(R.id.img_task_complete);
		cateTxt[4] = (TextView)findViewById(R.id.txt_task_complete);
		
		imgArrSelected[0] = R.drawable.task_add;
		imgArrCommon[0] = R.drawable.task_add2;
		
		imgArrSelected[1] = R.drawable.task_new;
		imgArrCommon[1] = R.drawable.task_new2;
		
		imgArrSelected[2] = R.drawable.task_reback;
		imgArrCommon[2] = R.drawable.task_reback2;
		
		imgArrSelected[3] = R.drawable.task_back;
		imgArrCommon[3] = R.drawable.task_back2;
		
		imgArrSelected[4] = R.drawable.task_complete;
		imgArrCommon[4] = R.drawable.task_complete2;
		
		initChildViews();
		
        myViewPager = (ViewPager)findViewById(R.id.view_pager);
        myViewPager.setAdapter(myAdapter);
        myViewPager.setOnPageChangeListener(new OnPageChangeListener() {
			@Override
			public void onPageScrollStateChanged(int arg0) {
			}
			@Override
			public void onPageScrolled(int arg0, float arg1, int arg2) {
			}
			@Override
			public void onPageSelected(int arg0) {
				toTran(arg0);
				
				if(preIndex != arg0) {
					cateIcon[arg0].setImageResource(imgArrSelected[arg0]);
					cateTxt[arg0].setTextColor(getResources().getColor(R.color.tb_person_category));
					
					cateIcon[preIndex].setImageResource(imgArrCommon[preIndex]);
					cateTxt[preIndex].setTextColor(getResources().getColor(R.color.tb_person_category2));
					
					preIndex = arg0; 
				}
				
//				if(arg0 == 0) {
//					toQueryAddPagerData();
//				} else if(arg0 == 1) {
//					toQueryNewPagerData();
//				} else if(arg0 == 2) {
//					toQueryRebackPagerData();
//				} else if(arg0 == 3) {
//					toQueryBackPagerData();
//				} else if(arg0 == 4) {
//					toQueryCompletePagerData();
//				}
			}
        });
        
        tranImg = (ImageView)findViewById(R.id.tranImg);
        tranImgWidth = (displayWidth - 2 * (UnitsUtils.dipToPx(20, scale))) / 5;
        tranImg.getLayoutParams().width = tranImgWidth;
        
        //获取任务类型列表
		new Thread(new Runnable() {
			
			@SuppressWarnings("static-access")
			@Override
			public void run() {
				// TODO Auto-generated method stub
				result = new ConnectWeb().httpPost(HttpUtils.DEFAULT_URL+"task/getTaskType.do","","");
				try {
					array = new JSONArray(result);
					sendMessage(1);
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
					sendMessage(2);
				} 
				if(result.equals("")){
					sendMessage(2);
				}
			}
		}).start();

	}
	
	public void onResume(){
		super.onResume();
		et_name.setText(UnitsUtils.getTimeNumberString());
	}
	
	/**
	 * 初始化五个页面的 View
	 */
	private void initChildViews() {
		proDialog = new ProgressDialog(this);
		proDialog.setMessage("正在加载……");
		proDialog.show();
		//初始化第一个
		parentAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, parentDicetString);
		sonAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, sonDicetString);
		add_sp_bigType = (Spinner) addLayout.findViewById(R.id.sp_big_category);
		add_sp_bigType.setOnItemSelectedListener(new OnItemSelectedListener() {

			@Override
			public void onItemSelected(AdapterView<?> arg0, View arg1,
					int arg2, long arg3) {
				// TODO Auto-generated method stub
				parentDicetString.clear();
				sonDicetString.clear();
				try {
					for(int i=0;i<array.length();i++){
						JSONObject jsonObj = new JSONObject(array.get(i).toString());
						parentDicetString.add(jsonObj.getJSONObject("dict").getString("dname"));
					}
					//将第一个父类型的子类加入到子类列表中
						//得到该父类的子类型集合
						JSONArray sonDicts = new JSONArray(new JSONObject(array.get(arg2).toString()).getString("dictList"));
						for(int m=0;m<sonDicts.length();m++){
							JSONObject jsonObj1 = new JSONObject(sonDicts.get(m).toString());
							sonDicetString.add(jsonObj1.getString("dname"));
						}
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			
			add_sp_smallType.setAdapter(sonAdapter);
			}

			@Override
			public void onNothingSelected(AdapterView<?> arg0) {
				// TODO Auto-generated method stub
				
			}
		});
		et_name = (TextView) addLayout.findViewById(R.id.et_name);
		add_sp_smallType = (Spinner) addLayout.findViewById(R.id.sp_small_category);
		add_task_detail = (EditText) addLayout.findViewById(R.id.et_nation);//任务描述
		add_task_cardno = (EditText) addLayout.findViewById(R.id.et_cardno);
		add_bt_add = (Button) addLayout.findViewById(R.id.bt_add);
		add_task_cardno.setOnClickListener(this);
		add_bt_add.setOnClickListener(this);
		//初始化第二个
		newTaskListView = (ListView) newLayout.findViewById(R.id.tasklist);
		jianduTaskListView = (ListView) rebackLayout.findViewById(R.id.tasklist);
		tuihuiTaskListView = (ListView) backLayout.findViewById(R.id.tasklist);
		doneTaskListView = (ListView) completeLayout.findViewById(R.id.tasklist);
		newTaskListView.setOnItemClickListener(listListener1);
		jianduTaskListView.setOnItemClickListener(listListener2);
		tuihuiTaskListView.setOnItemClickListener(listListener3);
		doneTaskListView.setOnItemClickListener(listListener4);
	}
	
	public void chooseUploadImage(View view) {
		
	}
	
    private class MyPagerAdapter extends PagerAdapter{
		@Override
		public void destroyItem(View arg0, int arg1, Object arg2) {
			((ViewPager)arg0).removeView(mListViews.get(arg1));
		}

		@Override
		public void finishUpdate(View arg0) {
		}

		@Override
		public int getCount() {
			return mListViews.size();
		}

		@Override
		public Object instantiateItem(View view, int pos) {
			((ViewPager)view).addView(mListViews.get(pos),0);
			return mListViews.get(pos);
		}

		@Override
		public boolean isViewFromObject(View arg0, Object arg1) {
			return arg0==(arg1);
		}

		@Override
		public void restoreState(Parcelable arg0, ClassLoader arg1) {
		}

		@Override
		public Parcelable saveState() {
			return null;
		}

		@Override
		public void startUpdate(View arg0) {
		}
		
		@Override
		public void notifyDataSetChanged() {
			super.notifyDataSetChanged();
		}
    }
    
    private int displayWidth;
    private float scale;
    private void initDisplayInfo() {
    	Display display = getWindowManager().getDefaultDisplay();
        displayWidth = display.getWidth();
        
        scale = getResources().getDisplayMetrics().density;
    }
    
    int pagerPos = 0;
    float padding = 37.5f;
    public void toTran(int newPos) {
    	translateAnimation(newPos);
        pagerPos = newPos;
        //新任务页面，加载新任务信息
        switch(newPos){
        case 1:
        	proDialog.show();
    		new Thread(new Runnable() {
    			
    			@Override
    			public void run() {
    				// TODO Auto-generated method stub
    				result = new ConnectWeb().httpPost(HttpUtils.DEFAULT_URL+"task/getNewTask.do","name",commonBean.getName());
    				try {
    					taskArray = new JSONArray(result);
    					sendMessage(3);
    				} catch (JSONException e) {
    					// TODO Auto-generated catch block
    					e.printStackTrace();
    					sendMessage(2);
    				} 
    				if(result.equals("")){
    					sendMessage(2);
    				}
    			}
    		}).start();
    		break;
        case 2:
        	proDialog.show();
    		new Thread(new Runnable() {
    			
    			@Override
    			public void run() {
    				// TODO Auto-generated method stub
    				result = new ConnectWeb().httpPost(HttpUtils.DEFAULT_URL+"task/getJianDuTask.do","name",commonBean.getName());
    				try {
    					taskArray = new JSONArray(result);
    					sendMessage(4);
    				} catch (JSONException e) {
    					// TODO Auto-generated catch block
    					e.printStackTrace();
    					sendMessage(2);
    				} 
    				if(result.equals("")){
    					sendMessage(2);
    				}
    			}
    		}).start();
        	break;
        case 3:
        	proDialog.show();
    		new Thread(new Runnable() {
    			
    			@Override
    			public void run() {
    				// TODO Auto-generated method stub
    				result = new ConnectWeb().httpPost(HttpUtils.DEFAULT_URL+"task/getTuiHuiTask.do","name",commonBean.getName());
    				try {
    					taskArray = new JSONArray(result);
    					sendMessage(5);
    				} catch (JSONException e) {
    					// TODO Auto-generated catch block
    					e.printStackTrace();
    					sendMessage(2);
    				} 
    				if(result.equals("")){
    					sendMessage(2);
    				}
    			}
    		}).start();
        	break;
        case 4:
        	proDialog.show();
    		new Thread(new Runnable() {
    			
    			@Override
    			public void run() {
    				// TODO Auto-generated method stub
    				result = new ConnectWeb().httpPost(HttpUtils.DEFAULT_URL+"task/getDoneTask.do","name",commonBean.getName());
    				try {
    					taskArray = new JSONArray(result);
    					sendMessage(6);
    				} catch (JSONException e) {
    					// TODO Auto-generated catch block
    					e.printStackTrace();
    					sendMessage(2);
    				} 
    				if(result.equals("")){
    					sendMessage(2);
    				}
    			}
    		}).start();
        	break;
        }
        
    }
    
    private void translateAnimation(int newPos) {
    	
    	TranslateAnimation tran = new TranslateAnimation((tranImgWidth * pagerPos), (tranImgWidth * newPos), 0, 0);
    	tran.setDuration(400);
    	tran.setFillAfter(true);
    	tranImg.setAnimation(tran);
    }

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch(v.getId()){
		case R.id.et_cardno:
			Intent intent = new Intent(mContext,TBTaskAttachment.class);
			startActivity(intent);
			break;
		case R.id.bt_add:
			if(myConstants.imgAtt1Path==""||
					myConstants.imgAtt1Path1==""||
					myConstants.recordePath==""){
				 Toast.makeText(mContext, "请补齐附件", Toast.LENGTH_SHORT).show();
				 return;
			}
			files[0] = new File(myConstants.imgAtt1Path);
			files[1] = new File(myConstants.imgAtt1Path1);
			files[2] = new File(myConstants.imgAtt1Path2);
			files[3] = new File(myConstants.recordePath);
			uploadFiles(files);
		}
	}
	
    public void sendMessage(int what){
    	msg = handler.obtainMessage();
		msg.what=what;
		handler.sendMessage(msg);
    }

	
	//新增任务
	public void addTask(){
		
	}
	
	public void toAddPage(View view){
		myViewPager.setCurrentItem(0);
	}
	
	public void toNewPage(View view){
		myViewPager.setCurrentItem(1);
	}
	
	public void toJianDuPage(View view){
		myViewPager.setCurrentItem(2);
	}
	
	public void toTuiHuiPage(View view){
		myViewPager.setCurrentItem(3);
	}
	
	public void toDonePage(View view){
		myViewPager.setCurrentItem(4);
	}
	
	//提交带附件的表单
    public void uploadFiles(File[] imageFiles) {
//        Log.i(TAG, "upload start");
    	proDialog.show();
        try {
            String requestUrl = HttpUtils.DEFAULT_URL+"task/addTask.do";
            //请求普通信息
            Map<String, String> params = new HashMap<String, String>();
            params.put("taskNo", et_name.getText().toString());
            params.put("bigType", add_sp_bigType.getSelectedItem().toString());
            params.put("smallType", add_sp_smallType.getSelectedItem().toString());
            params.put("name",commonBean.getName());
            params.put("taskDetail", add_task_detail.getText().toString());
            //上传文件,第三个参数是struts2接收的参数
            FormFile formfile0 = new FormFile(imageFiles[0].getName(), imageFiles[0], "image0", "application/octet-stream");
            FormFile formfile1 = new FormFile(imageFiles[1].getName(), imageFiles[1], "image1", "application/octet-stream");
            FormFile formfile2 = new FormFile(imageFiles[1].getName(), imageFiles[1], "image2", "application/octet-stream");
            FormFile formfile3 = new FormFile(imageFiles[2].getName(), imageFiles[2], "image3", "application/octet-stream");
            Boolean result = FileUtil.post(requestUrl, params, new FormFile[]{formfile0,formfile1,formfile2,formfile3});
            if(result){
            	proDialog.cancel();
            	 Toast.makeText(mContext, "提交成功！", Toast.LENGTH_SHORT).show();
            }else{
            	proDialog.cancel();
            	 Toast.makeText(mContext, "提交失败", Toast.LENGTH_SHORT).show();
            }
//            Toast.makeText(mContext, "success", Toast.LENGTH_SHORT).show();
        } catch (Exception e) {
        	proDialog.cancel();
        	Toast.makeText(mContext, "提交失败", Toast.LENGTH_SHORT).show();
            e.printStackTrace();
        }
    }
    
    //显示任务列表的适配器
    BaseAdapter taskListAdapter = new BaseAdapter() {
		
		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			// TODO Auto-generated method stub
			if(convertView==null){
				convertView = LayoutInflater.from(mContext).inflate(R.layout.tbtask_item, null);
			}
			TextView textDetail = (TextView) convertView.findViewById(R.id.item_task_detail);
//			TextView textBigType = (TextView) convertView.findViewById(R.id.item_task_bigType);
//			TextView textSmallType = (TextView) convertView.findViewById(R.id.item_task_samllType);
			TextView textCreatDate = (TextView) convertView.findViewById(R.id.item_task_time);
			try {
				textDetail.setText((new JSONObject(taskArray.get(position).toString()).getString("tdetail")));
//				textBigType.setText((new JSONObject(taskArray.get(position).toString()).getString("tbtype")));
//				textSmallType.setText((new JSONObject(taskArray.get(position).toString()).getString("tstype")));
				textCreatDate.setText((new JSONObject(taskArray.get(position).toString()).getString("createTime")));
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			return convertView;
		}
		
		@Override
		public long getItemId(int arg0) {
			// TODO Auto-generated method stub
			return arg0;
		}
		
		@Override
		public Object getItem(int arg0) {
			// TODO Auto-generated method stub
			return arg0;
		}
		
		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return taskArray.length();
		}
	};
    
	private OnItemClickListener listListener1 = new OnItemClickListener() {

		@Override
		public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
				long arg3) {
			// TODO Auto-generated method stub
			
			try {
				Intent intent = new Intent();
				intent.putExtra("staute", "1");
				intent.setClass(mContext, TBTaskDetailActivity.class);
				intent.putExtra("task", taskArray.get(arg2).toString());
				startActivity(intent);
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	};
	
	private OnItemClickListener listListener2 = new OnItemClickListener() {

		@Override
		public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
				long arg3) {
			// TODO Auto-generated method stub
			
			try {
				Intent intent = new Intent();
				intent.putExtra("staute", "5");
				intent.setClass(mContext, TBTaskDetailActivity.class);
				intent.putExtra("task", taskArray.get(arg2).toString());
				startActivity(intent);
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	};
	
	private OnItemClickListener listListener3 = new OnItemClickListener() {

		@Override
		public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
				long arg3) {
			// TODO Auto-generated method stub
			
			try {
				Intent intent = new Intent();
				intent.putExtra("staute", "6");
				intent.setClass(mContext, TBTaskDetailActivity.class);
				intent.putExtra("task", taskArray.get(arg2).toString());
				startActivity(intent);
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	};
	
	private OnItemClickListener listListener4 = new OnItemClickListener() {

		@Override
		public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
				long arg3) {
			// TODO Auto-generated method stub
			
			try {
				Intent intent = new Intent();
				intent.putExtra("staute", "7");
				intent.setClass(mContext, TBTaskDetailActivity.class);
				intent.putExtra("task", taskArray.get(arg2).toString());
				startActivity(intent);
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	};
    
}
